<?php
class User_Contact
{
    const _CONST_TB_DEFAULT_ = 'user_contact';
    

    public static function get($uid)
    {
        $query = DB::select()
        ->from(self::_CONST_TB_DEFAULT_)
        ->where('uid', '=', $uid)
        ->execute();

        if ($query->valid())
        {
            $info = $query->current();
            return $info;
        }
        else
        {
            return NULL;
        }
    }

    public static function email($uid)
    {
        $info = self::get($uid);
        return Arr::get($info, 'email', '');
    }

    public static function set($uid, $info)
    {
        if (self::has($uid))
        {
            unset($info['uid']);
            if (empty($info))
            {
                return false;
            }
            return self::update($uid, $info);
        }
        else
        {
            $info['uid'] = $uid;
            return self::insert($info);
        }
    }

    protected static function has($uid)
    {
        $query = DB::select(array('count("uid")', 'count'))
        ->from(self::_CONST_TB_DEFAULT_)
        ->where('uid', '=', $uid);
        return (bool) $query->execute()->get('count');
    }

    protected static function update ($uid, $info)
    {
        $query = DB::update(self::_CONST_TB_DEFAULT_)
        ->set($info)
        ->where('uid', '=', $uid);
        return $query->limit(1)->execute();
    }

    protected static function insert($info)
    {
        list($insert_id, $rows) = DB::insert(self::_CONST_TB_DEFAULT_)
        ->columns (array_keys($info))
        ->values  (array_values($info))
        ->execute();

        return $rows;
    }
}